package day2;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * Servlet implementation class AddUser
 */
@WebServlet(urlPatterns = { "/AddUser" }, name = "AddUser")
public class AddUser extends HttpServlet {
	private static final long serialVersionUID = 1L;

	Connection con;
	Context ctx;
	DataSource ds;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		/*
		 * resp.setContentType("text/html"); PrintWriter out = resp.getWriter();
		 * out.write("post method not supported.<br>"); out.close();
		 */doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		out.write("Server Message: ");
		String userName = req.getParameter("userName");
		String password = req.getParameter("password");
		try {
			ctx = new InitialContext();
			ds = (DataSource) ctx.lookup("jdbc/mydata");
			con = ds.getConnection();

			PreparedStatement p = con
					.prepareStatement("INSERT INTO MyWebUsers Values(?,?)");
			p.setString(1, userName);
			p.setString(2, password);
			p.executeUpdate();
			out.write("User Credentials Succcessfully stored.<br>");
			p.close();
			con.close();
		} catch (Exception e) {
			out.write(e.toString() + ".<br>");
		}
		out.close();
	}
}
